// Modules to control application life and create native browser window
const { app, ipcMain, dialog, BrowserWindow } = require('electron');
const process = require('process');
const window = require('./window');
const { startServer } = require('./server');

console.log(`* 🚀 启动客户端应用程序`);

let winInstance = null; // BrowserWindow实例

// 启动Chrome命令行
app.commandLine.appendSwitch('lang', 'zh_CN');

function initialize() {
  /** 确保只有个应用实例 */
  let isGetLock = app.requestSingleInstanceLock();
  if (!isGetLock) {
    /** 没有拿到锁，说明app已经被启动了 */
    app.quit(); // app 退出
    process.exit(0); // 当前进程结束
  }

  /** app 被第二次启动 */
  app.on('second-instance', () => {
    if (winInstance) {
      if (winInstance.isMinimized()) winInstance.restore();
      winInstance.focus();
      winInstance.show();
    } else {
      winInstance = window.create();
    }
  });

  app.on('ready', async () => {
    try {
      // 启动服务
      await startServer();
      winInstance = window.create();
    } catch (error) {
      if (error.code == 'EADDRINUSE') {
        dialog.showErrorBox('端口被占用！', '请关闭其他程序或重启计算机');
        app.quit();
      } else {
        dialog.showErrorBox('启动失败', '初始化应用失败，请卸载后重新安装');
        app.quit();
      }
    }
  });

  app.on('activate', () => {
    // 针对 macOS
    if (BrowserWindow.getAllWindows().length === 0) createWindow();
  });

  app.on('window-all-closed', () => {
    // 针对 macOS
    app.quit();
  });

  // GPU进程崩溃
  app.on('gpu-process-crashed', () => {
    console.log('App crashed!!!');
    app.exit(0);
  });
}

initialize();

/** app 退出 */
ipcMain.on('quit', () => {
  app.quit();
  process.exit(0);
});
